package com.sunshine.litemusic.fragment.music;

import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatSeekBar;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.sunshine.litemusic.R;
import com.sunshine.litemusic.callback.MyCallBack;
import com.sunshine.litemusic.fragment.search.SearchModel;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author sunshine
 * @date 2020/5/29
 * 音乐播放器界面
 */
public class MusicFragment extends Fragment implements View.OnClickListener{

    private ImageView album, start, before, next, background;
    private AppCompatTextView songName, singerName, nowTime, totalTime;
    private AppCompatSeekBar seekBar;
    private MusicViewModel viewModel;
    private Date date;
    private SimpleDateFormat simpleDateFormat;
    private static MediaPlayer mediaPlayer = new MediaPlayer();
    private int nowPosition;
    private ArrayList<SearchModel.SearchBean> searchBeanArrayList;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_music, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        viewModel = new ViewModelProvider(this).get(MusicViewModel.class);

        album = getView().findViewById(R.id.imageView_al);
        start = getView().findViewById(R.id.imageView_start);
        before = getView().findViewById(R.id.imageView_before);
        next = getView().findViewById(R.id.imageView_next);
        background = getView().findViewById(R.id.background);
        nowTime = getView().findViewById(R.id.textView_nowtime);
        totalTime = getView().findViewById(R.id.textView_totaltime);
        songName = getView().findViewById(R.id.song_name);
        singerName = getView().findViewById(R.id.singser_name);
        seekBar = getView().findViewById(R.id.seekBar);

        date = new Date();
        simpleDateFormat = new SimpleDateFormat("mm:ss");

        start.setOnClickListener(this);
    }

    /**
     * 播放搜索的歌曲
     * @see com.sunshine.litemusic.activity.main.MainActivity
     * @param searchBeanArrayList 要播放的歌曲列表
     * @param position 当前播放的位序
     */
    public void searchPlay(ArrayList<SearchModel.SearchBean> searchBeanArrayList, int position){
        nowPosition = position; //当前位序记录，切换歌曲时需要以这个为参考
        this.searchBeanArrayList = searchBeanArrayList;

        toPlay(searchBeanArrayList.get(position).getId());

        //上下曲控制按钮
        before.setOnClickListener(this);
        next.setOnClickListener(this);

        //快进快退滑动条
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                date.setTime(progress);
                nowTime.setText(simpleDateFormat.format(date));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mediaPlayer.seekTo(seekBar.getProgress());
            }
        });
    }

    /**
     * 播放组件
     * @param id 歌曲id，用于获取播放地址
     */
    private void toPlay(int id){
        Glide.with(this)
                .load(searchBeanArrayList.get(nowPosition).getAl().getPicUrl())
                .into(album);
        System.out.println(searchBeanArrayList.get(nowPosition).getAl().getPicUrl());
        songName.setText(searchBeanArrayList.get(nowPosition).getName());
        singerName.setText(searchBeanArrayList.get(nowPosition).getAr());
        try {
            mediaPlayer.reset();
            start.setImageDrawable(getResources().getDrawable(R.drawable.ic_start));
            nowTime.setText("00:00");
            totalTime.setText("00:00");

        }catch (Exception e){ }

        viewModel.getMusicUrl(id, new MyCallBack() {
            @Override
            public <T, S> void callBack(T bean, S bean1) {  //这里bean1并不需要，始终传入null
                try {
                    mediaPlayer.setDataSource(((MusicBean.MusicInfoBean)bean).getUrl());
                    mediaPlayer.prepareAsync();
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mediaPlayer.start();
                            start.setImageDrawable(getResources().getDrawable(R.drawable.ic_pause));
                            Date totalDate = new Date();
                            totalDate.setTime(mediaPlayer.getDuration());
                            totalTime.setText(simpleDateFormat.format(totalDate));
                            seekBar.setMax(mediaPlayer.getDuration());
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


        //开启新线程获取实时播放位置
        Thread thread = new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    while (true){
                        sleep(1000);    //为了防止内存占用过多，需要休眠
                        if (mediaPlayer.isPlaying()){
                            //注意更新ui界面需要切换到主线程
                            handler.sendEmptyMessage(1);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
    }

    //主线程更新ui界面
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    date.setTime(mediaPlayer.getCurrentPosition());
                    nowTime.setText(simpleDateFormat.format(date));
                    if (0 != mediaPlayer.getCurrentPosition()){
                        seekBar.setProgress(mediaPlayer.getCurrentPosition());
                    }
                    break;
            }
        }
    };

    //按钮点击接口
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.imageView_start:
                try {
                    if (mediaPlayer.isPlaying()){
                        mediaPlayer.pause();
                        start.setImageDrawable(getResources().getDrawable(R.drawable.ic_start));
                    }else {
                        mediaPlayer.start();
                        start.setImageDrawable(getResources().getDrawable(R.drawable.ic_pause));
                    }
                }catch (Exception e){}
                break;
            case R.id.imageView_before:
                if (0 == nowPosition) nowPosition = searchBeanArrayList.size();
                toPlay(searchBeanArrayList.get(--nowPosition).getId());
                break;
            case R.id.imageView_next:
                if (searchBeanArrayList.size() - 1 == nowPosition) nowPosition = -1;
                toPlay(searchBeanArrayList.get(++nowPosition).getId());
                break;

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaPlayer.release();
    }
}
